package com.chhuang.ewcrm.controller;

import com.chhuang.ewcrm.bean.QueryBean;
import com.chhuang.ewcrm.consts.EwcrmConstants;
import com.chhuang.ewcrm.entity.ANotice;
import com.chhuang.ewcrm.entity.AUserNotice;
import com.chhuang.ewcrm.entity.SysUser;
import com.chhuang.ewcrm.service.ANoticeService;
import com.chhuang.ewcrm.service.AUserNoticeService;
import com.chhuang.ewcrm.service.SysUserService;
import com.chhuang.ewcrm.vo.ResultBean;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * (ANotice)表控制层
 *
 * @author chhuang
 * @since 2020-11-28 11:50:16
 */
@RestController
@RequestMapping("/service/aNotice")
public class ANoticeController {
    Logger logger = LoggerFactory.getLogger(ANoticeController.class);
    /**
     * 服务对象
     */
    @Resource
    private ANoticeService aNoticeService;
    @Resource
    private AUserNoticeService aUserNoticeService;
    @Resource
    private SysUserService sysUserService;

    @PutMapping("/editOne")
    public ResultBean<?> editANotice(@RequestBody ANotice aNotice, HttpSession session){
        ResultBean<?> resultBean = new ResultBean<>();
        resultBean.setSuccess(false);

        Object obj = session.getAttribute(EwcrmConstants.SessionConst.SYS_USER);
        if(aNotice!=null && obj!=null && StringUtils.isNotEmpty(aNotice.getTitle()) &&
                StringUtils.isNotEmpty(aNotice.getNoticeContent())){
            SysUser user = (SysUser) obj;
            Date now = new Date();
            aNotice.setUserId(user.getUserId());
            aNotice.setUsername(user.getUsername());
            aNotice.setFullname(user.getFullname());
            aNotice.setCreateTime(now);
            aNotice = aNoticeService.insert(aNotice);
            //通知到用户
            List<SysUser> users = sysUserService.query(null);
            if(users!=null && !users.isEmpty()){
                List<AUserNotice> aUserNotices = new LinkedList<>();
                for(SysUser item: users){
                    AUserNotice aUserNotice = new AUserNotice();
                    aUserNotice.setUserId(item.getUserId());
                    aUserNotice.setSenderName(StringUtils.isEmpty(user.getFullname())?user.getUsername():user.getFullname());
                    aUserNotice.setNoticeId(aNotice.getNoticeId());
                    aUserNotice.setTitle(aNotice.getTitle());
                    String content = aNotice.getNoticeContent();
                    aUserNotice.setBriefContent(content.length()>127?content.substring(0, 124)+"...":content);
                    aUserNotice.setStatus(0);//未读
                    aUserNotice.setCreateTime(now);
                    aUserNotices.add(aUserNotice);
                }
                aUserNoticeService.insertBatch(aUserNotices);
            }
            resultBean.setSuccess(true);
        }else {
            resultBean.setMessage("参数为空或者用户没有登录");
        }

        return resultBean;
    }

    /**
     * 删除通知
     * @param noticeId
     * @return
     */
    @DeleteMapping("/removeOne/{noticeId}")
    public ResultBean<?> removeOne(@PathVariable("noticeId") String noticeId){
        ResultBean<?> resultBean = new ResultBean<>();
        resultBean.setSuccess(true);
        if(StringUtils.isNotEmpty(noticeId)){
            //删除通知
            resultBean.setSuccess(this.aNoticeService.deleteById(noticeId));
            //删除用户通知
            if(resultBean.isSuccess()) deleteUserNotice(noticeId);
        }else{
            resultBean.setSuccess(false);
            resultBean.setMessage("参数不为空");
        }
        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 根据id列表批量删除
     * @param noticeIds
     * @return
     */
    @PutMapping("/removeList")
    public ResultBean<?> removeList(@RequestBody List<String> noticeIds){
        ResultBean<?> resultBean = new ResultBean<>();
        if(noticeIds!=null && !noticeIds.isEmpty()){
            resultBean.setSuccess(this.aNoticeService.deleteByIds(noticeIds)>0);
            if(resultBean.isSuccess())
                noticeIds.forEach(this::deleteUserNotice);
        }else{
            resultBean.setSuccess(false);
            resultBean.setMessage("参数不为空");
        }
        logger.debug(resultBean.toString());
        return resultBean;
    }

    private void deleteUserNotice(String noticeId) {
        if(StringUtils.isNotEmpty(noticeId)){
            AUserNotice aUserNotice = new AUserNotice();
            aUserNotice.setNoticeId(noticeId);
            aUserNoticeService.deleteByEntity(aUserNotice);
        }
    }

    /**
     * 表格查询
     * @param queryBean
     * @return
     */
    @PostMapping("/queryPage")
    public ResultBean<PageInfo<ANotice>> query(@RequestBody QueryBean<ANotice> queryBean){
        logger.debug(queryBean.toString());
        ResultBean<PageInfo<ANotice>> resultBean = new ResultBean<>();

        PageInfo<ANotice> pageInfo = null;
        List<ANotice> notices = null;
        if(queryBean!=null) {
            if (StringUtils.isNotEmpty(queryBean.getOrderBy()))
                pageInfo = aNoticeService.search(queryBean.getSearch(), queryBean.getPageNum(), queryBean.getPageSize(), queryBean.getOrderBy());
            else
                pageInfo = aNoticeService.search(queryBean.getSearch(), queryBean.getPageNum(), queryBean.getPageSize());
            resultBean.setData(pageInfo);
            resultBean.setSuccess(true);
            resultBean.setCode(queryBean.getDraw());
        }else {
            resultBean.setSuccess(false);
            resultBean.setMessage("参数不为空");
        }

        logger.debug(resultBean.toString());
        return resultBean;
    }

}